#include "log.h"


void logEntry(SOCKET s, httprequestp req, httpresponsep res) {
	FILE *logfile;
	SOCKADDR_IN temp;		
	int siz = sizeof(temp);
	time_t ltime;

	time(&ltime);

	if (getpeername(s,(struct sockaddr*) &temp,&siz) < 0 )
		perror("erros");	

	logfile = fopen(getLogFileName(),"a");
	if ( logfile == NULL )
		printf("can't open %s", getLogFileName());

	fprintf(logfile,"\n%s	%s %d\t", ctime(&ltime),inet_ntoa(temp.sin_addr), temp.sin_port);
	if ( req->http_command )
		fprintf(logfile,"Request: GET ");
	else
		fprintf(logfile,"Request: Unsupported command ");
	fprintf(logfile, "%s %s\tResponse: %s %s %s", req->filename, "HTTP/1.1","HTTP/1.1", res->code, res->msg);
	fclose(logfile);
}

void sendLog(SOCKET s) {
	FILE *logfile;
	char *log;
	int len;

	logfile = fopen(getLogFileName(),"rb");
	if ( logfile == NULL )
		printf("can't open %s", getLogFileName());

	fseek(logfile, 0, SEEK_END);
	len = ftell(logfile);

	log = (char*) malloc(len*sizeof(char));

	rewind(logfile);
	len = fread(log, sizeof(char), len, logfile);
	
	send(s, log, len, 0);

	fclose(logfile);
	free(log);
}

